const app = getApp()
import util from '../../../utils/util'
import {
  SelectMember,
  GetRedListCategory,
  GetTemplateConfig,
  UpRedLlist
} from '../../../config/api'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    model: 1,
    member: '', // 用户缓存信息
    curTab: 0,
    isShowPopup: false, // 是否显示姓名弹出
    allName: [],
    tid: '',
    tname: '',
    curIndex: '', //当前选中
    imgs: [],
    count: 0,
    baseURL: '',
    compressImgsSizeArr: [],
    allMeanus: [], //所有子菜单
    array1: [],
    id1s: [],
    array2: ['2', '2', '2', '2'],
    array3: ['3', '3', '3', '3'],
    s: [],
    index1: 0,
    index2: 0,
    index3: 0,
    allMeanu: [],
    id: 0,
    t: 0,
    content: "",
    showView: true,
    tmplIds: [], // 模板消息id集合
  },

  onLoad: function(options) {
    let model = wx.getStorageSync('model')
    if (model) {
      this.setData({
        model
      })
    }
    let member = wx.getStorageSync('member')
    let grider_storge = wx.getStorageSync('grider')

    if (member) {
      this.setData({
        member
      })
    } else if (grider_storge && !member) {
      wx.showModal({
        showCancel: false,
        content: '您暂不能操作此功能',
        success(res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '/pages/index/index',
            })
          }
        }
      })
      return;
    } else {
      wx.redirectTo({
        url: '/pages/register/register',
      })
      return;
    }

    let that = this;
    //加载无限级菜单接口
    let pames = {
      'type': 2,
      'pid': 0,
      vollege_id: app.globalData.vollege_id
    };

    util.apiRequest(GetRedListCategory, pames, null).then(r => {
      console.log('无限级菜单数据：', r.data.data);
      let allMeanus = [];
      allMeanus.push(r.data.data);
      console.log('初始化allMeanus：', allMeanus)
      that.setData({
        allMeanus: allMeanus,
        allMeanu: r.data.data,
        s: [0]
      });
      console.log("onLoad", that.data.s)
    });

    this.getTmplIds(); // 调用模板id集合

  },

  chose: function(e) {
    console.log('选择时e:', e)
    let that = this;
    let t = e.currentTarget.dataset.index
    let pid = e.currentTarget.dataset.pid

    let allMeanus = []
    let allMeanus1 = that.data.allMeanus
    console.log('t', t)
    console.log('pid', pid)

    that.setData({
      showView: false
    })

    for (var i = 0; i <= t; i++) {
      allMeanus.push(allMeanus1[i])
    }
    let pames = {
      'type': 2,
      'pid': pid,
      vollege_id: app.globalData.vollege_id
    };
    util.apiRequest(GetRedListCategory, pames, null).then(r => {
      console.log('chose', r.data.data);
      let allMeanus1 = that.data.allMeanus;
      allMeanus1.push(r.data.data);
      console.log(allMeanus1)
      that.setData({
        allMeanus: allMeanus,
        allMeanu: r.data.data,
        t: t
      });
      console.log("chose_s", that.data.s)
    });

  },

  setm: function(e) {
    console.log('value', e);
    let that = this;
    let index = that.data.s
    let t = that.data.t

    console.log("length", index.length)

    if (index[t] == undefined) {
      index.push(e.currentTarget.dataset.k)
      index.push(0)
    } else {
      index[t] = e.currentTarget.dataset.k
      index[t + 1] = 0;
    }
    //return;

    console.log('setm_t', t);
    console.log('setm_index', index);
    //return false;
    that.setData({
      s: index,
      id: e.currentTarget.dataset.id,
      curIndex: index[t]
    })
    console.log('s', index)
    let id = e.currentTarget.dataset.id

    that.setms()

  },

  setms: function() {
    let that = this;
    if (that.data.id == 0) {
      wx.showToast({
        title: '请选择一项',
        icon: 'success',
        duration: 2000
      })
      return false;
    }
    let pid = that.data.id
    let pames = {
      'type': 2,
      'pid': pid,
      vollege_id: app.globalData.vollege_id
    };

    let allMeanus1 = that.data.allMeanus;
    let t = 0;

    for (var i = 0; i < allMeanus1.length; i++) {
      for (var j = 0; j < allMeanus1[i].length; j++) {
        if (pid == allMeanus1[i][j].id) {
          t = i + 1;
        }
      }
    }
    util.apiRequest(GetRedListCategory, pames, null).then(r => {
      console.log('无限级菜单数据：', r.data.data);
      if (r.data.data.length == 0) {
        that.setData({
          showView: true
        })
      }

      if (r.data.data.length > 0) {
        allMeanus1.push(r.data.data);
        console.log(allMeanus1)
        that.setData({
          allMeanus: allMeanus1,
          allMeanu: r.data.data,
          t: t,
          id: 0
        });
      }

      console.log('红榜名称：', that.data.allMeanus)

    });
  },

  onSelectPerson(e) {
    console.log('e', e)
    let index = e.currentTarget.dataset.index;
    if (index == 0) {
      this.setData({
        isShowPopup: false
      })
    }
    this.setData({
      curTab: index
    })
  },

  onSearchName(e) {
    console.log(e)
    let name = e.detail.value;
    console.log('name', name)
    if (name != '') {
      this.setData({
        isShowPopup: true
      })
      util.apiRequest(SelectMember, {
        name: name,
        vollege_id: app.globalData.vollege_id
      }, null).then(r => {
        console.log('搜索：', r)
        this.setData({
          allName: r.data.data
        })
      })
    } else {
      this.setData({
        tname: '',
        isShowPopup: false
      })
    }
  },

  onConfirmName(e) {
    console.log('选择姓名', e)
    let tid = e.currentTarget.dataset.id;
    let tname = e.currentTarget.dataset.name;
    this.setData({
      tid: tid,
      tname: tname,
      isShowPopup: false
    })
  },

  close: function() {
    let that = this;
    that.setData({
      showView: (!that.data.showView)
    })
  },

  bindTextAreaBlur: function(e) {
    this.setData({
      content: e.detail.value
    })
    console.log("text", e.detail.value)
  },


  // 上传图片
  chooseImg: function(e) {
    //console.log('选择图片e', e)
    var that = this;
    var imgs = this.data.imgs;
    let uploadFile = ''; //最后处理完，图片上传的图片地址

    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        //  console.log('图片', res.tempFilePaths)
        var tempFilePaths = res.tempFilePaths;
        // var imgs = [];
        wx.showLoading({
          title: '上传中',
        })
        for (let i = 0; i < tempFilePaths.length; i++) {
          let index = that.data.count;
          let canvasId = 'canvasId' + index; // canvas id
          console.log('canvasId', canvasId)
          //获得原始图片大小
          wx.getImageInfo({
            src: tempFilePaths[i],
            success(res) {
              console.log('原始图片r', res)
              var originWidth, originHeight;
              originHeight = res.height;
              originWidth = res.width;
              //压缩比例
              // 最大尺寸限制
              var maxWidth = 800,
                maxHeight = 600;
              // 目标尺寸
              var targetWidth = originWidth,
                targetHeight = originHeight;

              //等比例压缩，如果宽度大于高度，则宽度优先，否则高度优先
              if (originWidth > maxWidth || originHeight > maxHeight) {
                console.log('图片过大需要压缩')
                if (originWidth / originHeight > maxWidth / maxHeight) {
                  // 要求宽度*(原生图片比例)=新图片尺寸
                  targetWidth = maxWidth;
                  targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                } else {
                  targetHeight = maxHeight;
                  targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                }
              }

              //更新canvas大小
              let compressObj = {},
                compressImgsSizeArr = that.data.compressImgsSizeArr;
              compressObj['index'] = index;
              compressObj['cw'] = targetWidth;
              compressObj['ch'] = targetHeight;
              compressImgsSizeArr.push(compressObj)

              that.setData({
                compressImgsSizeArr: compressImgsSizeArr
              });

              //尝试压缩文件，创建 canvas
              var ctx = wx.createCanvasContext(canvasId);
              ctx.clearRect(0, 0, targetWidth, targetHeight);
              ctx.drawImage(tempFilePaths[i], 0, 0, targetWidth, targetHeight);

              //console.log('图片尺寸数组', that.data.compressImgsSizeArr)

              //保存图片
              ctx.draw(false,
                setTimeout(function() {
                  wx.canvasToTempFilePath({
                    canvasId: canvasId,
                    width: targetWidth,
                    height: targetHeight,
                    destWidth: targetWidth,
                    destHeight: targetHeight,
                    quality: 0.5,
                    success: (res) => {
                      console.log('压缩后', res)
                      uploadFile = res.tempFilePath;
                      wx.uploadFile({
                        url: app.globalData.baseURL + '/api/WxProgramApi/upload',
                        filePath: uploadFile,
                        name: 'file',
                        header: {
                          "Content-Type": "multipart/form-data"
                        },
                        formData: {
                          'file': tempFilePaths
                        },
                        success(res) {
                          console.log('图片上传成功', res)
                          let data = JSON.parse(res.data);
                          if (res.statusCode == 200) {
                            var imgSrc = data.data;
                            console.log('图片服务器地址', imgSrc)
                            that.data.imgs.push(imgSrc);
                            console.log('图片数组', imgs)
                            that.setData({
                              imgs: that.data.imgs
                            })
                            wx.hideLoading()
                          }
                        },
                        fail(res) {
                          console.log('上传失败')
                        }
                      })

                    },
                    fail: (err) => {
                      console.error(err)
                    }
                  }, this)
                }, 1000)
              );

            }
          })

          let count = ++that.data.count;
          console.log('++count', count)
          that.setData({
            count: count
          })
          //console.log('循环后count', that.data.count)
        }
      }
    });
  },

  // 删除图片
  deleteImg: function(e) {
    var imgs = this.data.imgs;
    var compressImgsSizeArr = this.data.compressImgsSizeArr;
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    compressImgsSizeArr.splice(index, 1);
    this.setData({
      imgs: imgs,
      compressImgsSizeArr: compressImgsSizeArr
    })
  },


  // 预览图片
  previewImg: function(e) {
    let that = this;
    //获取当前图片的下标
    var index = e.currentTarget.dataset.index;
    console.log('预览index', index)
    //所有图片
    var imgType = e.currentTarget.dataset.imgtype;
    var imgs = this.data.imgs;

    let newimgs = imgs.map(function(item) {
      console.log(item)
      return that.data.baseURL + item;
    })

    console.log('预览时imgs', imgs)
    console.log(this.data.baseURL + imgs[index])
    wx.previewImage({
      //当前显示图片
      current: newimgs[index],
      //所有图片
      urls: newimgs
    })
  },

  getTmplIds() { // 获取模板消息id集合
    let that = this;
    util.apiRequest(GetTemplateConfig, {
      vollege_id: app.globalData.vollege_id
    }, null).then(r => {
      console.log('模板id：', r)
      let tmplIds = r.data.data.map(item => {
        return item.value.template_id
      })
      console.log('66tmplIds:', tmplIds)
      that.setData({
        tmplIds
      })
    })
  },

  //提交表单
  sumbit: function() {
    let catpid = '';
    let that = this;
    let cat_name = "";
    let allMeanus = that.data.allMeanus;
    let member = wx.getStorageSync("member");
    console.log("allMeanus", allMeanus);
    console.log('ss', that.data.s)

    if (that.data.s.length == 1) {
      wx.showModal({
        showCancel: false,
        content: '请选择加分项目',
      })
      return;
    }

    if (this.data.curTab == 1 && this.data.tname == '') {
      wx.showModal({
        showCancel: false,
        content: '请填写他人姓名',
      })
      return;
    }

    let s = that.data.s;

    for (var i = 0; i < s.length - 1; i++) {
      console.log('iii:', i)
      catpid += allMeanus[i][s[i]].id + ","
      cat_name += allMeanus[i][s[i]].title + ","
    }

    let k = s.length - 2;
    let cat_id = allMeanus[k][s[k]].id;

    if (this.data.curTab == 1) {
      var prams = {
        'uid': member.id,
        'u_name': member.name,
        'catpid': catpid,
        'cat_id': cat_id,
        'cat_name': cat_name,
        'content': that.data.content,
        'thumb': that.data.imgs,
        tid: that.data.tid,
        t_name: that.data.tname,
        vollege_id: app.globalData.vollege_id,
        town_id: this.data.member.town_id
      }
    } else {
      var prams = {
        'uid': member.id,
        'u_name': member.name,
        'catpid': catpid,
        'cat_id': cat_id,
        'cat_name': cat_name,
        'content': that.data.content,
        'thumb': that.data.imgs,
        vollege_id: app.globalData.vollege_id,
        town_id: this.data.member.town_id
      }
    }

    util.apiRequest(UpRedLlist, prams).then(r => {
      console.log('提交表单', r);
      wx.requestSubscribeMessage({
        tmplIds: that.data.tmplIds,
        success(res) {
          console.log('成功', res)
        }
      })
      if (r.data.code == 1) {
        wx.showModal({
          showCancel: false,
          content: r.data.info,
          success(res) {
            if (res.confirm) {
              wx.redirectTo({
                url: "/pages/culture/redList/redList"
              })
            }
          }
        })
      }
    })

    console.log("catpid", catpid);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})